package com.qf.realm;

import com.alibaba.druid.util.StringUtils;
import com.qf.service.MenuService;
import com.qf.service.RoleService;
import com.qf.service.UserService;
import com.qf.pojo.SysUsers;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @ClassName MyUserRealm
 * @Author xiao宋
 * @Date 16:06  2022/10/10
 * @Version 1.0
 * @Description TODO
 */
public class MyUserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUsers user = (SysUsers) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> roles = roleService.findRolesByUserId(user.getId());
        authorizationInfo.setRoles(roles);
        Set<String> pr = menuService.findPermisByUserId(user.getId());
        authorizationInfo.setStringPermissions(pr);

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username=(String) token.getPrincipal();
        String password=new String((char[])token.getCredentials());

        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            throw new RuntimeException("用户名或密码为空");
        }

        SysUsers user=userService.findByname(username);
        if (user==null){
            throw new UnknownAccountException("用户不存在");
        }
        if (user.getStatus()==0){
            throw new LockedAccountException("账户已锁定");
        }
        String pwd=user.getPassword();
        if (!password.equalsIgnoreCase(pwd)){
            throw new CredentialsException("密码错误");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), user.getRealname());

        return info;
    }
}
